package com.example.demo.order.security;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.example.demo.order.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;
import java.util.TreeMap;

/**
 * @ClassName OrderSecurityUtil
 * @Description 订单安全工具类
 * @Author MingChang.Wei
 * @Date 2025/9/26
 **/
@Slf4j
@Component
public class OrderSecurityUtil {
    
    private static final String SIGN_KEY = "your_secret_key_here"; // 实际项目中应从配置文件读取
    
    /**
     * 参数签名验证
     */
    public boolean verifySign(Map<String, Object> params, String sign) {
        if (StrUtil.isBlank(sign)) {
            return false;
        }
        
        String calculatedSign = generateSign(params);
        return sign.equals(calculatedSign);
    }
    
    /**
     * 生成参数签名
     */
    public String generateSign(Map<String, Object> params) {
        // 按key排序
        TreeMap<String, Object> sortedParams = new TreeMap<>(params);
        
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : sortedParams.entrySet()) {
            if (entry.getValue() != null && !"sign".equals(entry.getKey())) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        
        // 添加密钥
        sb.append("key=").append(SIGN_KEY);
        
        return DigestUtil.md5Hex(sb.toString());
    }
    
    /**
     * 验证用户权限
     */
    public void validateUserPermission(Long currentUserId, Long targetUserId) {
        if (!currentUserId.equals(targetUserId)) {
            log.warn("用户权限验证失败: currentUserId={}, targetUserId={}", currentUserId, targetUserId);
            throw new BusinessException("无权限访问该用户数据");
        }
    }
    
    /**
     * 验证金额合法性
     */
    public void validateAmount(BigDecimal amount) {
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessException("金额必须大于0");
        }
        
        // 限制最大金额（防止异常大额订单）
        BigDecimal maxAmount = new BigDecimal("100000");
        if (amount.compareTo(maxAmount) > 0) {
            throw new BusinessException("单笔订单金额不能超过10万元");
        }
    }
    
    /**
     * 验证商品数量
     */
    public void validateQuantity(Integer quantity) {
        if (quantity == null || quantity <= 0) {
            throw new BusinessException("商品数量必须大于0");
        }
        
        // 限制最大数量（防止恶意刷单）
        if (quantity > 999) {
            throw new BusinessException("单个商品数量不能超过999");
        }
    }
    
    /**
     * 记录敏感操作日志
     */
    public void logSensitiveOperation(String operation, Long userId, Object data) {
        log.info("敏感操作记录: operation={}, userId={}, data={}", 
                operation, userId, JSONUtil.toJsonStr(data));
    }
}
